<template>
  <view class="user-login">
    <view v-if="userInfoShow" class="user-login__avatar">
      <view class="user-login__avatar--img"
        ><img :src="avatarUrl" alt="" srcset=""
      /></view>
      <view class="user-login__avatar--img-txt">{{ userName }}</view>
    </view>
    <view class="user-login__title">
      为了给您提供更好的服务体验，在您登录注册过程中，我们将分步获取您的头像昵称和手机号码，我们将遵循相关法律，合理收集、存储，使用以上信息。
    </view>
    <view class="user-login--icon-list">
      <view class="user-login--icon-cell">
        <view class="user-login--icon"
          ><img
            src="https://kc-glasses-mall-langjing.oss-cn-chengdu.aliyuncs.com/2024/09/23/a6aa6442a8d349b1bad9d43f342dbcd2logo.png"
            alt=""
            srcset=""
        /></view>
        <view class="user-login--icon--txt">
          <view class="user-login--icon--top">头像昵称</view>
          <view class="user-login--icon--bottom">将作为个人特色信息展示</view>
        </view>
      </view>
      <view class="user-login--icon-cell">
        <view class="user-login--icon"
          ><img
            src="https://kc-glasses-mall-langjing.oss-cn-chengdu.aliyuncs.com/2024/09/23/94785bcf248948609ef20486a3ecd572phone.png"
            alt=""
            srcset=""
        /></view>
        <view class="user-login--icon--txt">
          <view class="user-login--icon--top">手机号</view>
          <view class="user-login--icon--bottom"
            >将作为您在本平台用户氛围的唯一认证信息</view
          >
        </view>
      </view>
    </view>
    <view class="agreement-wrap am-flex-rc-center">
      <u-checkbox
        v-model="agreeCheck"
        :disabled="checkDisabled"
        shape="circle"
        active-color="#4bb019"
      ></u-checkbox>
      登录代表您已同意
      <text class="agree-list" @click="goToPrivacy" style="color: skyblue"
        >《用户协议》。</text
      >
    </view>

    <button
      class="user-login__button--info"
      type="primary"
      :loading="loginLoading"
      open-type="getPhoneNumber"
      @getphonenumber="getPhoneNumberCb"
      :disabled="loginLoading"
      v-if="userInfoShow"
    >
      手机号码快捷登录
    </button>
    <button
      v-if="!userInfoShow"
      class="user-login__button--info"
      @click="getUserInfo"
    >
      授权头像昵称
    </button>
    <view class="center"
      ><text @click="gotoIndex" style="color: skyblue">暂不登录</text></view
    >
    <u-popup v-model="showLogin" mode="bottom" height="60%">
      <view class="login-method">
        <view class="login-method-title am-flex-row-center">
          <image :src="NAV_BAR_TITLE" class="login-method-img" />
          <view class="login-method-close" @click="closePopup">
            <u-icon name="close" color="#999" size="32rpx"></u-icon>
          </view>
        </view>
        <scroll-view>
          <view class="login-method-list">
            <u-form label-width="200">
              <u-form-item
                required
                label="登录身份:"
                prop="currentLogin"
                borderBottom
                align="right"
              >
                <u-radio-group v-model="currentLogin" placement="row">
                  <u-radio
                    input-align="right"
                    v-for="(item, index) in loginMethod"
                    :key="index"
                    :name="item.value"
                  >
                    {{ item.name }}
                  </u-radio>
                </u-radio-group>
              </u-form-item>
            </u-form>

            <u-form label-width="300" ref="uForm">
              <view
                v-for="(item, index) in form"
                :key="index"
                v-if="currentLogin == 2"
              >
                <u-form-item
                  required
                  :label="'学生' + (index == 0 ? '' : index + 1) + '姓名:'"
                  prop="studentName"
                  borderBottom
                >
                  <u-input
                    type="text"
                    input-align="right"
                    placeholder="请输入学生姓名"
                    v-model="item.studentName"
                    :disabled="disabled[index]"
                  >
                  </u-input>
                </u-form-item>
                <u-form-item
                  required
                  :label="'学生' + (index == 0 ? '' : index + 1) + '关系:'"
                  prop="studentRelation"
                  borderBottom
                >
                  <u-input
                    type="text"
                    input-align="right"
                    placeholder="请输入与学生关系"
                    v-model="item.studentRelation"
                    :disabled="disabled[index]"
                  >
                  </u-input>
                </u-form-item>
                <u-form-item
                  required
                  :label="'学生' + (index == 0 ? '' : index + 1) + '身份证号:'"
                  prop="studentIdNum"
                  borderBottom
                >
                  <u-input
                    maxlength="18"
                    type="text"
                    input-align="right"
                    placeholder="请输入学生身份证号"
                    v-model="item.studentIdNum"
                    :disabled="disabled[index]"
                  >
                  </u-input>
                </u-form-item>
              </view>
            </u-form>

            <button
              v-if="currentLogin == 2"
              type="primary"
              class="add-btn"
              hover-class="button-hover"
              @click="addStudent"
            >
              新增
            </button>
          </view></scroll-view
        >

        <view class="login-method-btn">
          <button
            class="u-reset-button co-primary-button login-button"
            hover-class="co-primary-button--hover"
            @click="refuseHandle"
          >
            拒绝
          </button>
          <button
            class="u-reset-button co-primary-button login-button"
            hover-class="co-primary-button--hover"
            @click="confirmHandle"
          >
            确认登录
          </button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { NAV_BAR_TITLE } from '@/types/navbar.js'
import { apiUserPhone, apiwxLogin, getStudentByTel } from '@/api/user.js'
import { apiGetOpenId } from '@/api/order'
export default {
  data() {
    return {
      loginLoading: false,
      userInfoShow: false,
      userName: '',
      avatarUrl: '',
      userPhone: '',
      openid: '',
      agreeCheck: '',
      checkDisabled: false,
      showLogin: false,
      NAV_BAR_TITLE,
      loginMethod: [
        { loginType: 1, name: '游客身份', value: 1 },
        { loginType: 2, name: '家长身份', value: 2 }
      ],
      form: [
        {
          studentName: '',
          studentIdNum: '',
          studentRelation: ''
        }
      ],
      currentLogin: 2,
      studentDTOList: [],
      disabled: [false]
      // rules: {
      //   studentName: {
      //     type: 'string',
      //     required: true,
      //     message: '请填写学生姓名',
      //     trigger: ['blur', 'change']
      //   },
      //   studentRelation: {
      //     type: 'string',
      //     required: true,
      //     message: '请填写与学生关系',
      //     trigger: ['blur', 'change']
      //   },
      //   studentIdNum: {
      //     type: 'string',
      //     required: true,
      //     message: '请填写学生身份证号',
      //     trigger: ['blur', 'change']
      //   }
      // }
    }
  },
  onReady() {
    this.form.forEach((element, i) => {
      this.$refs.uForm.setRules(this.rules)
    })
  },
  methods: {
    getStudentByTelHandle(data) {
      getStudentByTel({ agentPhone: data }).then((res) => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.studentDTOList = res.data.data
          if (this.studentDTOList.length) {
            this.form = this.studentDTOList
          }
          this.studentDTOList.forEach((e, i) => {
            this.disabled[i] = true
            this.disabled.push()
          })
        }
      })
    },
    addStudent() {
      uni.showModal({
        title: '温馨提示',
        content: `您已经添加过学生信息，是否分享给其它家庭成员完成爱心传递任务，继续添加学生后，需要分享给${
          this.form.length + 1
        }人才可领取奖励。`,
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if (confirm) {
            let flag = false
            this.form.forEach((e) => {
              if (!e.studentName || !e.studentIdNum || !e.studentRelation) {
                flag = false
              } else {
                flag = true
              }
            })
            if (flag == false) {
              uni.showModal({
                title: '温馨提示',
                content: '请补全已存在的学生信息',
                showCancel: true,
                success: ({ confirm, cancel }) => {}
              })
            } else {
              this.form.push({
                studentName: '',
                studentIdNum: '',
                studentRelation: ''
              })
            }
          }
        }
      })
    },
    closePopup() {
      this.showLogin = false
      this.form = [
        {
          studentName: '',
          studentIdNum: '',
          studentRelation: ''
        }
      ]
      // this.$refs.uForm.resetFields()
    },
    refuseHandle() {
      this.showLogin = false
      this.currentLogin = 2
      this.form = [
        {
          studentName: '',
          studentIdNum: '',
          studentRelation: ''
        }
      ]
    },
    confirmHandle() {
      let flag = false
      this.form.forEach((e) => {
        if (!e.studentName || !e.studentIdNum || !e.studentRelation) {
          flag = false
        } else {
          flag = true
        }
      })
      if (flag == false && this.currentLogin == 2) {
        uni.showModal({
          title: '温馨提示',
          content: '请补全学生信息',
          showCancel: true,
          success: ({ confirm, cancel }) => {}
        })
        return
      }
      let params
      console.log(this.form, 'formformformformform')
      if (this.currentLogin == 1) {
        params = {
          img: this.avatarUrl,
          nickname: this.userName,
          openid: this.openid,
          phone: this.userPhone,
          proxyType: 0
        }
      } else if (this.currentLogin == 2) {
        // this.$refs.uForm.validate((valid) => {
        // if (valid) {
        params = {
          img: this.avatarUrl,
          nickname: this.userName,
          openid: this.openid,
          phone: this.userPhone,
          proxyType: 1,
          studentDTOList: this.form
        }
        // } else {
        //   console.log('请补全信息！')
        // }
        // })
      }
      apiwxLogin(params).then(({ data: resdata }) => {
        console.log(resdata, '----------')
        console.log(resdata?.data?.userInfo)
        if (resdata.code == 200) {
          this.$store.commit('SET_USER_INFO', resdata?.data?.userInfo)
          this.$store.commit('SET_USER_TOKEN', resdata?.data?.token)
          this.$store.commit('SET_OPEN_ID', resdata?.data?.userInfo.openid)
          this.$store.dispatch('getNoticeData')
          this.showLogin = false
          uni.switchTab({
            url: '/pages/index/index'
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: resdata.msg
          })
        }
      })
      // 用获取的手机号去登录
    },

    /**
     * @name 微信获取用户手机号信息操作
     * @param data
     * @return {*}
     */
    getPhoneNumberCb(event) {
      // 微信获取手机号api
      console.log('getPhoneNumberCb')
      console.log(event)
      if (this.loginLoading) return
      let code = event?.detail?.code
      console.log(code)
      code
        ? apiUserPhone({
            code
          })
            .then(({ data }) => {
              console.log(data)
              // 获取到真实手机号
              this.userPhone = data?.data
              console.log(this.userPhone)
              this.showLogin = true
              this.getStudentByTelHandle(this.userPhone)
            })
            .catch((err) => {
              console.log(err)
            })
        : uni.showToast({
            icon: 'none',
            title: '手机号获取失败！'
          })
    },
    /**
     * @name 用户授权获取账户信息
     * @param data
     * @return {*}
     */
    getUserInfo() {
      if (!this.agreeCheck) {
        uni.showToast({
          icon: 'none',
          title: '请阅读用户协议、隐私政策并勾选！'
        })
        return
      }
      uni.login({
        provider: 'weixin',
        onlyAuthorize: true,
        success: (loginRes) => {
          console.log(loginRes, '++++++++++++++++++++')
          apiGetOpenId({ code: loginRes.code })
            .then((res) => {
              console.log(res)
              let { code, data, msg } = res.data
              if (code == 200) {
                // 获取成功
                this.openid = data.openid
                this.$store.commit('SET_OPEN_ID', data.openid)
              }
            })
            .catch((err) => {})
        },
        fail: function (err) {
          uni.showToast({
            icon: 'none',
            title: '用户数据获取失败！'
          })
        }
      })
      uni.getUserProfile({
        desc: '用于完善用户信息', //必填，声明获取用户个人信息后的用途，不超过30个字符
        success: (res) => {
          console.log(res, '_+_+_+_+_++_+_')
          uni.showToast({
            icon: 'none',
            title: '获取成功'
          })
          this.userName = res?.userInfo?.nickName
          this.avatarUrl = res?.userInfo?.avatarUrl
          this.userInfoShow = true
          this.checkDisabled = true
        },
        fail: (err) => {
          console.log(err)
          uni.showToast({
            icon: 'none',
            title: '用户拒绝获取'
          })
        }
      })
    },
    goToPrivacy() {
      uni.navigateTo({
        url: '/pages/login/privacy-policy'
      })
    },
    gotoIndex() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  }
}
</script>

<style lang="scss">
.user-login {
  position: relative;
  height: 100vh;
  background: url('https://kc-glasses-mall-langjing.oss-cn-chengdu.aliyuncs.com/2024/09/23/1d5bb007c65545f58f13a4a30c229773bg.png')
    no-repeat left top;
  background-size: contain;
  // 头像
  &__avatar {
    position: absolute;
    top: 80rpx;
    left: 10%;
    display: flex;
    width: 80%;
    margin: auto;
    &--img {
      width: 100rpx;
      height: 100rpx;
      margin-right: 30rpx;
      ._img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
      &-txt {
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        color: #333333;
      }
    }
  }
  // 标题
  &__title {
    width: 80%;
    margin: 0rpx auto 100rpx auto;
    padding-top: 250rpx;
    font-weight: 400;
    color: #666666;
  }
  // 图标
  &--icon {
    width: 80rpx;
    height: 80rpx;
    margin-right: 30rpx;
    ._img {
      width: 100%;
      height: 100%;
    }
    &-list {
      width: 80%;
      margin: auto;
      margin-bottom: 180rpx;
    }
    &-cell {
      display: flex;
      margin: 75rpx 0;
    }
    &--txt {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    &--top {
      font-size: 26rpx;
      color: #333;
    }
    &--bottom {
      font-size: 24rpx;
      color: #999999;
    }
  }
  // 按钮
  &__button {
    &--info {
      width: 90%;
      margin: auto;
      margin-top: 117rpx;
      background: linear-gradient(132deg, #fe6507 0%, #f69027 100%);
      border-radius: 40px;
      color: #fff;
    }
  }
  .agreement-wrap {
    color: #999999;
    ::v-deep {
      .u-checkbox__icon-wrap--disabled {
        background-color: #4bb019 !important;
      }
    }
  }
}
.center {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20rpx;
  // margin-bottom: 10px;
}
.login-method {
  padding: 45rpx 45rpx;
  position: relative;
  z-index: 1;
}
.login-method-title {
  position: relative;
  font-weight: bold;
  font-size: 34rpx;
  color: #fa3534;
  text-align: center;
  padding: 30rpx 0;
}
.login-method-text {
  padding: 25rpx 0;
  color: #333;
}
.login-method-close {
  position: absolute;
  top: 30rpx;
  right: 0;
  z-index: 99;
}
.login-method-item {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
  &:last-child {
    border-bottom: 0;
  }
}
.login-method-btn {
  margin-top: 40rpx;
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}
.login-method-img {
  width: 192rpx;
  height: 40rpx;
  line-height: 80rpx;
}
.login-button {
  width: 40%;
}
.add-btn {
  margin-top: 20rpx;
  float: right;
  width: 100rpx;
  height: 40rpx;
  line-height: 40rpx;
  font-size: 24rpx;
  padding: 0;
  color: #fff;
}
</style>
